package com.xiaouyudeguang.common.resource;

import com.xiaouyudeguang.common.annotation.ApiMapping;
import com.xiaouyudeguang.common.entity.CodeBody;
import com.xiaouyudeguang.common.entity.Field;
import com.xiaouyudeguang.common.exception.BusinessException;
import com.xiaouyudeguang.common.executor.ExcelExecutor;
import com.xiaouyudeguang.common.respose.ResultDto;
import com.xiaouyudeguang.common.utils.JavaType;
import com.xiaouyudeguang.common.utils.PingYinUtils;
import com.xiaouyudeguang.common.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

@Slf4j
@RestController
@RequestMapping("/code")
public class CodeController {

    @PostMapping(value = "/execute")
    public ResultDto<Boolean> execute(@RequestBody CodeBody codeBody) throws Exception {
        return ResultDto.ok(codeBody.execute());
    }

    @PostMapping(value = "/transform")
    public ResultDto<Object> transform(@RequestBody CodeBody codeBody) throws Exception {
        List<Field> fields = new ArrayList<>();
        for (Map.Entry<String, String> entry : codeBody.getColumns().entrySet()) {
            String javaType = JavaType.getJavaType(entry.getValue());
            if (StringUtils.isNotBlank(javaType)) {
                String columnName = codeBody.isToPinyin() ? PingYinUtils.transform(entry.getKey()) : entry.getKey();
                fields.add(Field.builder().name(columnName).comment(entry.getKey()).type(entry.getValue()).build());
            } else if (Pattern.compile("[\u4e00-\u9fa5]").matcher(entry.getKey()).find()) {
                fields.add(Field.builder().name(entry.getValue()).comment(entry.getKey()).type("VARCHAR(50)").build());
            } else {
                fields.add(Field.builder().name(entry.getKey()).comment(entry.getValue()).type("VARCHAR(50)").build());
            }
        }
        return ResultDto.ok(fields);
    }

    @ApiMapping(value = "/upload", method = RequestMethod.POST, tags = "导入")
    public ResultDto<Object> upload(String tenantId, String appId, MultipartFile file) throws Exception {
        if (file.getSize() > 26214400) {
            throw new BusinessException("上传文件不能大于25MB");
        }
        ExcelExecutor.execute(file.getInputStream());
        return ResultDto.ok();
    }
}